package com.reservation.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.reservation.common.BusinessException;
import com.reservation.entity.Exhibition;
import com.reservation.entity.Guide;
import com.reservation.entity.GuideReservation;
import com.reservation.entity.User;
import com.reservation.mapper.ExhibitionMapper;
import com.reservation.mapper.GuideMapper;
import com.reservation.mapper.GuideReservationMapper;
import com.reservation.mapper.UserMapper;
import com.reservation.service.GuideReservationService;
import com.reservation.service.GuideService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * 解说员预约服务实现类
 */
@Service
public class GuideReservationServiceImpl implements GuideReservationService {

    @Autowired
    private GuideReservationMapper guideReservationMapper;

    @Autowired
    private GuideMapper guideMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ExhibitionMapper exhibitionMapper;

    @Autowired
    private GuideService guideService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public GuideReservation createReservation(GuideReservation reservation) {
        // 检查用户是否存在
        User user = userMapper.selectById(reservation.getUserId());
        if (user == null) {
            throw new BusinessException("用户不存在");
        }

        // 检查解说员是否存在
        Guide guide = guideMapper.selectById(reservation.getGuideId());
        if (guide == null) {
            throw new BusinessException("解说员不存在");
        }

        // 检查解说员状态是否为可用
        if (!"AVAILABLE".equals(guide.getStatus())) {
            throw new BusinessException("该解说员当前不可预约");
        }

        // 检查展览是否存在
        Exhibition exhibition = exhibitionMapper.selectById(reservation.getExhibitionId());
        if (exhibition == null) {
            throw new BusinessException("展览不存在");
        }

        // 检查展览状态是否为进行中
        if (!"IN_PROGRESS".equals(exhibition.getStatus())) {
            throw new BusinessException("该展览当前不可预约");
        }

        // 检查预约日期是否在展览时间范围内
        LocalDate reservationDate = reservation.getReservationDate();
        if (reservationDate.isBefore(exhibition.getStartDate()) || reservationDate.isAfter(exhibition.getEndDate())) {
            throw new BusinessException("预约日期不在展览时间范围内");
        }

        // 检查解说员在指定时间段是否可预约
        if (!guideService.checkGuideAvailable(reservation.getGuideId(), reservationDate, reservation.getTimeSlot())) {
            throw new BusinessException("该解说员在指定时间段已被预约");
        }

        // 检查用户是否已经预约过该解说员的同一时间段
        if (checkUserHasReservation(reservation.getUserId(), reservation.getGuideId(), reservationDate, reservation.getTimeSlot())) {
            throw new BusinessException("您已预约过该解说员的同一时间段");
        }

        // 设置预约状态和时间
        reservation.setStatus("PENDING");
        reservation.setCreateTime(LocalDateTime.now());
        reservation.setUpdateTime(LocalDateTime.now());

        // 保存预约信息
        guideReservationMapper.insert(reservation);

        return reservation;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public GuideReservation updateReservationStatus(Long id, String status) {
        // 检查预约是否存在
        GuideReservation reservation = guideReservationMapper.selectById(id);
        if (reservation == null) {
            throw new BusinessException("预约不存在");
        }

        // 更新状态
        GuideReservation updateReservation = new GuideReservation();
        updateReservation.setId(id);
        updateReservation.setStatus(status);
        updateReservation.setUpdateTime(LocalDateTime.now());
        guideReservationMapper.updateById(updateReservation);

        // 返回更新后的预约信息
        return guideReservationMapper.selectById(id);
    }

    @Override
    public GuideReservation getReservationById(Long id) {
        GuideReservation reservation = guideReservationMapper.selectById(id);
        if (reservation == null) {
            throw new BusinessException("预约不存在");
        }
        User user = userMapper.selectById(reservation.getUserId());
        Exhibition exhibition = exhibitionMapper.selectById(reservation.getExhibitionId());
        reservation.setUserName(user.getName());
        reservation.setExhibitionName(exhibition.getName());
        reservation.setPhone(user.getPhone());
        return reservation;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean cancelReservation(Long id) {
        // 检查预约是否存在
        GuideReservation reservation = guideReservationMapper.selectById(id);
        if (reservation == null) {
            throw new BusinessException("预约不存在");
        }

        // 检查预约状态是否可取消
        if ("CANCELED".equals(reservation.getStatus()) || "REJECTED".equals(reservation.getStatus())) {
            throw new BusinessException("该预约已取消或被拒绝");
        }

        // 更新状态为取消
        GuideReservation updateReservation = new GuideReservation();
        updateReservation.setId(id);
        updateReservation.setStatus("CANCELED");
        updateReservation.setUpdateTime(LocalDateTime.now());

        return guideReservationMapper.updateById(updateReservation) > 0;
    }

    @Override
    public IPage<GuideReservation> getUserReservations(Page<GuideReservation> page, Long userId, String status) {
        LambdaQueryWrapper<GuideReservation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(GuideReservation::getUserId, userId);

        if (StringUtils.isNotBlank(status)) {
            queryWrapper.eq(GuideReservation::getStatus, status);
        }

        queryWrapper.orderByDesc(GuideReservation::getCreateTime);

        Page<GuideReservation> guideReservationPage = guideReservationMapper.selectPage(page, queryWrapper);
        List<GuideReservation> records = guideReservationPage.getRecords();
        for (GuideReservation reservation : records) {
            Exhibition exhibition = exhibitionMapper.selectById(reservation.getExhibitionId());
            Guide guide = guideMapper.selectById(reservation.getGuideId());
            reservation.setExhibitionName(exhibition.getName());
            if (Objects.isNull(guide)){
                reservation.setGuideName("解说员已被管理删掉了");
            }else {
                reservation.setGuideName(guide.getName());
            }
        }
        return guideReservationPage;
    }

    @Override
    public IPage<GuideReservation> getGuideReservations(Page<GuideReservation> page, Long guideId, String status, LocalDate date) {
        LambdaQueryWrapper<GuideReservation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(GuideReservation::getGuideId, guideId);

        if (StringUtils.isNotBlank(status)) {
            queryWrapper.eq(GuideReservation::getStatus, status);
        }

        if (date != null) {
            queryWrapper.eq(GuideReservation::getReservationDate, date);
        }

        queryWrapper.orderByDesc(GuideReservation::getCreateTime);

        return guideReservationMapper.selectPage(page, queryWrapper);
    }

    @Override
    public IPage<GuideReservation> getExhibitionGuideReservations(Page<GuideReservation> page, Long exhibitionId, String status, LocalDate date) {
        LambdaQueryWrapper<GuideReservation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(GuideReservation::getExhibitionId, exhibitionId);

        if (StringUtils.isNotBlank(status)) {
            queryWrapper.eq(GuideReservation::getStatus, status);
        }

        if (date != null) {
            queryWrapper.eq(GuideReservation::getReservationDate, date);
        }

        queryWrapper.orderByDesc(GuideReservation::getCreateTime);

        return guideReservationMapper.selectPage(page, queryWrapper);
    }

    @Override
    public IPage<GuideReservation> getAllReservations(Page<GuideReservation> page, String status) {
        LambdaQueryWrapper<GuideReservation> queryWrapper = new LambdaQueryWrapper<>();


        if (StringUtils.isNotBlank(status)) {
            queryWrapper.eq(GuideReservation::getStatus, status);
        }


        queryWrapper.orderByDesc(GuideReservation::getCreateTime);

        Page<GuideReservation> guideReservationPage = guideReservationMapper.selectPage(page, queryWrapper);
        List<GuideReservation> records = guideReservationPage.getRecords();
        for (GuideReservation reservation : records) {
            Exhibition exhibition = exhibitionMapper.selectById(reservation.getExhibitionId());
            Guide guide = guideMapper.selectById(reservation.getGuideId());
            User user = userMapper.selectById(reservation.getUserId());
            reservation.setExhibitionName(exhibition.getName());
            reservation.setGuideName(guide.getName());
            reservation.setUserName(user.getName());
        }
        return guideReservationPage;
    }

    @Override
    public boolean checkUserHasReservation(Long userId, Long guideId, LocalDate date, String timeSlot) {
        LambdaQueryWrapper<GuideReservation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(GuideReservation::getUserId, userId);
        queryWrapper.eq(GuideReservation::getGuideId, guideId);
        queryWrapper.eq(GuideReservation::getReservationDate, date);
        queryWrapper.eq(GuideReservation::getTimeSlot, timeSlot);
        queryWrapper.in(GuideReservation::getStatus, "PENDING", "APPROVED");

        return guideReservationMapper.selectCount(queryWrapper) > 0;
    }

    @Override
    public List<GuideReservation> getUserAllReservations(Long userId) {
        LambdaQueryWrapper<GuideReservation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(GuideReservation::getUserId, userId);
        queryWrapper.orderByDesc(GuideReservation::getCreateTime);

        return guideReservationMapper.selectList(queryWrapper);
    }

    @Override
    public List<GuideReservation> getGuideAllReservations(Long guideId) {
        LambdaQueryWrapper<GuideReservation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(GuideReservation::getGuideId, guideId);
        queryWrapper.orderByDesc(GuideReservation::getCreateTime);

        return guideReservationMapper.selectList(queryWrapper);
    }

    @Override
    public List<GuideReservation> getExhibitionAllGuideReservations(Long exhibitionId) {
        LambdaQueryWrapper<GuideReservation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(GuideReservation::getExhibitionId, exhibitionId);
        queryWrapper.orderByDesc(GuideReservation::getCreateTime);

        return guideReservationMapper.selectList(queryWrapper);
    }

    @Override
    public boolean confirm(Long id) {
        // 检查预约是否存在
        GuideReservation reservation = guideReservationMapper.selectById(id);
        if (reservation == null) {
            throw new BusinessException("预约不存在");
        }

        // 检查预约状态是否可取消
        if ("APPROVED".equals(reservation.getStatus()) || "CONFIRM".equals(reservation.getStatus())) {
            throw new BusinessException("该预约已确认");
        }

        // 更新状态为取消
        GuideReservation updateReservation = new GuideReservation();
        updateReservation.setId(id);
        updateReservation.setStatus("APPROVED");
        updateReservation.setUpdateTime(LocalDateTime.now());

        return guideReservationMapper.updateById(updateReservation) > 0;
    }
}